<?php

class JobsController extends Zend_Controller_Action 
{
	private $m_AppUI; // bien luu thong tin dang nhap

	public function init()
	{
		$this->AppUI = Zend_Auth::getInstance()->getIdentity();

		$this->objJob = Application_Model_Jobs::getInstance();
		$this->objCommon = Application_Model_Common::getInstance();
		$this->view->objJob = $this->objJob;
		$this->view->objCommon = $this->objCommon;
	}

	public function indexAction()
	{
		$view_type = $this->_request->getParam('view_type');
		$this->view->type = $view_type;
		switch($view_type)
		{
			case 'industry':
				$arrGroupInd = array();
				$arrTmp = $this->objCommon->getGroupIndustries();
				foreach($arrTmp as $tmp)
					$arrGroupInd[ $tmp['GROUP_ID'] ] = $tmp;

				$arrIndustries = $this->objCommon->getIndustries(LANGUAGE, 1);
				foreach($arrIndustries as $ind)
				{
					if(! isset($arrGroupInd[ $ind['GROUP_ID'] ]) ) continue;
					$arrGroupInd[ $ind['GROUP_ID'] ]['INDUSTRIES'][] = $ind;
				}
				$this->view->arrGroups = $arrGroupInd;
				break;
			default:
				$this->view->arrLocations = $this->objCommon->getLocations(LANGUAGE, 1);
				break;
		}
	}

	public function searchAction()
	{	
		$params = array(
			'keywords' => trim($this->_request->getParam('keywords')),
			'industries' => $this->_request->getParam('industries'),
			'locations' => $this->_request->getParam('locations')
		);
		if($this->_request->getPost('action')=='search')
		{
			$params = array_change_key_case($params, CASE_UPPER);
			$strLink = $this->objJob->map_links($params);
			$this->_redirect($strLink);
		}
		$strData = $this->_request->getParam('data');
		$splits = explode(' ', $strData);
		array_pop($splits);
		if(!empty($splits))
		{
			$strQuery = implode(' ', $splits);
			$strQuery = preg_replace('/^(viec-lam|jobs)-/', '', $strQuery);
			$params['keywords'] =  str_replace('-', ' ', $strQuery);
		}
	
		if($query = $this->_request->getParam('query'))
		{
			if(preg_match_all('/([ecildv]\d+)/i', $query, $arr))
			{
				foreach($arr[0] as $m)
				{
					$k = $m{0};
					$v = substr($m, 1);
					switch($k)
					{
						case 'i': $params['industries'][] = (int)$v; break;
						case 'l': $params['locations'][] = (int)$v; break;
						case 'c': $params['level'] = (int)$v; break;
						case 's': $params['salary'] = $v; break;
						case 'f': $params['salary_from'] = (int)$v; break;
						case 't': $params['salary_to'] = (int)$v; break;
						case 'd': $params['days'] = (int)$v; break;
						case 'e': $params['comp_id'] = (int)$v; break;
						case 'v': $params['limit'] = (int)$v; break;
					}
				}
			}
		}
		$this->view->params = $params;
		if(empty($params['days'])) $params['days'] = 30;
		if(empty($params['limit'])) $params['limit'] = 30;
		$params['page'] = (int)$this->_request->getParam('page', 1);

		$this->view->arrItems = $this->objJob->search($params, $total);
		$this->view->totalJobs = $total;
		$params['total'] = $total;
		$intPage = $params['page'];
		$params['link'] = $this->objJob->map_links($params);
		$this->view->PAGE_LINKS = Common::generatePaginator($params);


		// title
		$arr = array(
			'[jobs]' => $total,
			'[keyword]' => empty($params['keywords']) ? '' : $params['keywords'],
			'[industry]' => empty($params['industries']) ? '' : _t('seo_search_industry').' '.$this->objCommon->getIndustry($params['industries']),
			'[location]' => empty($params['locations']) ? '' : _t('seo_search_location').' '.$this->objCommon->getLocation($params['locations']),
			'[company]' => '',
			'[level]' => $params['level'] > 0 ? _t('seo_search_level').' '.$this->objCommon->getLevel($params['level']) : '',
			'[date]' => date('d-m-Y'),
			'[page]' => $intPage > 1 ? _t('seo_search_page').' '.$intPage : ''
		);
		$c = 0;
		if(!empty($params['comp_id']))
		{
			if($arrEmp = $this->objJob->getEmployerInfo($params['comp_id']))
			{
				$arr['[company]'] = $arrEmp['COMPNAY_NAME'];
				$this->view->arrEmp = $arrEmp;
			}
		}
		else
		{
			foreach($arr as $k=>$v)
				if(!empty($v)) $c++;
		}
		$strTitle = Common::stripTags(strtr(_t('seo_search_job_title'), $arr));
		$strD = empty($arrEmp) ? 'seo_search_job_description' : 'seo_search_job_by_company_description';
		$strDescription = Common::stripTags(strtr(_t($strD), $arr));

		$this->view->objCommon = $this->objCommon;
		$this->view->objJob = $this->objJob;
		$this->view->headTitle($strTitle, 'SET');
		$this->view->headMeta()->setName('keywords', $strDescription);
		$this->view->headMeta()->setName('description', $strDescription);
		$this->view->arrTopIndustries = $this->objCommon->getIndustries(LANGUAGE, 3, 10);
	}

	public function detailAction()
	{
		if($job_id = $this->_request->getParam('job_id'))
			$job_id = $job_id;

		if($arrJob = $this->objJob->get($job_id))
		{
			if(!defined('PRINT_PAGE'))
			{
				// search similar jobs
				$this->view->arrJobRelates = $this->objJob->search(array(
					'keywords' => $arrJob['JOB_TITLE'],
					'locations' => $arrJob['LOCATIONS'],
					'page' => 1,
					'limit' => 11
				), $total);
				// counter
				//Counter::getInstance()->incree('jobs', (int)$job_id);
			}

			$this->view->arrCom = $this->objJob->getEmployerInfo($arrJob['COMP_ID']);
			$this->view->arrJob = $arrJob;
			$arr = array(
				'[title]' => Common::stripTags($arrJob['JOB_TITLE']),
				'[active_date]' => date('d-m-Y', strtotime($arrJob['ACTIVE_DATE'])),
				'[expired_date]' => date('d-m-Y', strtotime($arrJob['LASTDATE'])),
				'[company]' => $this->view->arrCom['COMPANY_NAME'],
				'[date]' => date('d-m-Y'),
				'[level]' => $this->objCommon->getJobLevel($arrJob['LEVEL_ID']),
				'[location]' => $this->objCommon->getLocation($arrJob['LOCATIONS']),
				'[industry]' => $this->objCommon->getIndustry($arrJob['INDUSTRIES'])
			);
			if($arrJob['LASTDATE']=='0000-00-00') $arr['[expired_date]'] =  date('d-m-Y', time()+60*60*24*45);
			$strTitle = strtr(_t('seo_job_title_detail'), $arr);
			$strDescription = strtr(_t('seo_job_description_detail'), $arr);

			$this->view->headTitle($strTitle, 'SET');
			$this->view->headMeta()->setName('description', $strDescription);
			if($this->AppUI->userid) $this->view->isApply = $this->objJob->isApply($this->AppUI->userid, $job_id);
		}
	}

	public function printAction()
	{
		$this->_helper->layout->disableLayout();
		define('PRINT_PAGE', true);
		$this->detailAction();
	}

	public function companyAction()
	{
		$comp_id = $this->_request->getParam('comp_id');
		if($arrCom = $this->objJob->getEmployerInfo($comp_id))
		{
			$this->view->arrCom = $arrCom;
			// search similar jobs
			$this->view->arrLastestJobs = $this->objJob->search(array(
				'comp_id' => $comp_id,
				'page' => 1,
				'limit' => 10
			), $total);

			$arr = array(
				'[company]' => Common::stripTags($arrCom['COMPANY_NAME']),
				'[intro]' => Common::stripTags($arrCom['COMPANY_INTRO'], 100),
				'[jobs]' => $total
			);
			$strTitle = strtr(_t('seo_company_title_detail'), $arr);
			$strDescription = strtr(_t('seo_company_description_detail'), $arr);

			$this->view->headTitle($strTitle, 'SET');
			$this->view->headMeta()->setName('description', $strDescription);
		}
	}

	public function applyAction()
	{
		if($this->AppUI->userid < 1) $this->_redirect(BASE_URL.'/login');

		$job_id = $this->_request->getParam('job_id');
		$arrJob = $this->objJob-> getJob($job_id);

		if($this->_request->getParam('apply_success'))
		{
			$this->view->apply_success = true;
			$this->view->arrRelates = $this->objJob->search(array(
				'keywords' => $this->AppUI->job_title,
				'locations' => $this->AppUI->job_locations,
				'limit' => 20
			), $total);
			return;
		}
		if($this->_request->getPost('action')=='apply')
		{
			$resume_id = $this->_request->getPost('resume_id'); 
			if($resume_id=='attach')
			{
				// upload file
				$configs = array(
					'exts' => 'doc,pdf,docx',
					'path' => ROOT_DIR.'/htdocs/resumes/'.date('Ym')
				);
				if(!file_exists($configs['path'])) mkdir($configs['path'], 0777, true);
				if($file = Upload::run('resume_file', $configs))
				{
					return $file;
				}
			}
			else
			{
				$arrResume = Application_Model_Resume::getInstance()->get($resume_id, $this->m_AppUI->member_id);
			}
			$arrApply = array(
				'job_id' => $job_id,
				'resume_id' => $resume_id,
				'member_id' => $this->AppUI->userid,
				'comp_id' => $arrJob['COMP_ID'],
				'created' => time(),
				'job_title' => $arrJob['JOB_TITLE'],
				'resume_title' => $arrResume['RESUME_TITLE'],
				'letter_id' => $this->_request->getPost('letter_id'),
				'letter_title' => $this->_request->getPost('letter_title'),
				'letter_content' => $this->_request->getPost('letter_content')
			);
			$this->objJob->saveApply($arrApply);
			// save to session lastest apply
			$this->AppUI->job_title = $arrJob['JOB_TITLE'];
			$this->AppUI->job_locations = $arrJob['LOCATIONS'];

			// email 
			$arrParams = array(
				'[JOB_TITLE]' => $arrJob['JOB_TITLE'],
				'[FIRSTNAME]' => $this->AppUI->firstname
			);
			//$arrEmail = Common::getEmailLayout('JSK_APPLY_JOB_NOTIFY');
			// suggest more jobs active to apply
			$this->_redirect(BASE_URL.'/apply/success');
		}
		// print apply form
		$this->view->arrJob = $arrJob;
		$this->view->arrResumes = Application_Model_Resume::getInstance()->getResumes($this->m_AppUI->member_id);
		$this->view->arrLetters = Application_Model_Jobcenter::getInstance()->getCoverLetters($this->AppUI->userid);
	}

	public function savejobAction()
	{
		if($this->AppUI->userid < 1) die(_t('you_must_login'));

		if(!$job_id = (int)$this->_request->getPost('job_id')) die(_t('data_error'));
		Application_Model_Jobcenter::getInstance()->saveJob($this->AppUI->userid, $job_id);
		die(_t('job_is_saved'));
	}
}